const express = require("express");
const jwt = require("jsonwebtoken");
const assert = require("http-assert");

const User = require("../../models/User");
const router = express.Router({
  mergeParams: true,
});

//用户登录
router.post("/register", async (req, res) => {
  const { username, password } = req.body;
  // 判断当前用户名是否被占用
  const user = await User.findOne({ username }).select("+pass");
  assert(!user, 422, "用户存在");
  const new_user = await User.create({ username, password});
  const token = jwt.sign({ id: new_user._id }, req.app.get("secret"));
  res.send({ token, new_user });
});

router.get("/register", (req, res) => {
  res.send("login api ok");
});

module.exports = router;
